package com.petdog.common.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 阿里云视频点播服务工具类
 */
@Component
public class AliyunVodUtils {

    @Value("${spring.vod.aliyun.access-key-id}")
    private String accessKeyId;
    
    @Value("${spring.vod.aliyun.access-key-secret}")
    private String accessKeySecret;
    
    @Value("${spring.vod.aliyun.region}")
    private String regionId;
    
    private DefaultAcsClient client;
    
    @PostConstruct
    public void init() {
        // 初始化阿里云视频点播客户端
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        client = new DefaultAcsClient(profile);
    }
    
    /**
     * 获取视频播放地址
     * @param videoId 视频ID
     * @param expireTime 过期时间（秒）
     * @return 播放地址
     * @throws ClientException 客户端异常
     */
    public String getVideoPlayUrl(String videoId, Long expireTime) throws ClientException {
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        request.setVideoId(videoId);
        request.setAuthTimeout(expireTime);
        
        GetPlayInfoResponse response = client.getAcsResponse(request);
        List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
        if (playInfoList != null && !playInfoList.isEmpty()) {
            return playInfoList.get(0).getPlayURL();
        }
        return null;
    }
    
    /**
     * 获取视频上传凭证和上传地址
     * @return 上传凭证和地址
     * @throws ClientException 客户端异常
     */
    public CreateUploadVideoResponse createUploadVideo(String title, String fileName) throws ClientException {
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        request.setTitle(title);
        request.setFileName(fileName);
        return client.getAcsResponse(request);
    }
    
    /**
     * 刷新视频上传凭证
     * @param videoId 视频ID
     * @return 刷新后的凭证
     * @throws ClientException 客户端异常
     */
    public RefreshUploadVideoResponse refreshUploadVideo(String videoId) throws ClientException {
        RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
        request.setVideoId(videoId);
        return client.getAcsResponse(request);
    }
    

    
    /**
     * 删除视频
     * @param videoId 视频ID
     * @throws ClientException 客户端异常
     */
    public void deleteVideo(String videoId) throws ClientException {
        DeleteVideoRequest request = new DeleteVideoRequest();
        request.setVideoIds(videoId);
        client.getAcsResponse(request);
    }
}